package com.xinnet.mms.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.acegisecurity.providers.encoding.MessageDigestPasswordEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.login.service.EmpService;

/**
 * 
 *类描述：用户登录
 *
 * @author 李丽华[lilihua@xinnet.com]
 *
 * @version 1.0
 *
 * @since 2014-1-21
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {
	
	private static Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired 
	EmpService empService;
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping(value = "/loginPage")
	public String loginPage(HttpServletRequest request) {
		String result = "market/login";
		return result;
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@ResponseBody
	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	public void doLogin(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8"); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter printWriter = response.getWriter();
		HttpSession session=request.getSession();
		log.info(session.getMaxInactiveInterval());
		/*session.setMaxInactiveInterval(60*60*6);*/
		String rand=(String) session.getAttribute("rand");
		String userRand = request.getParameter("userRand");
		if(!rand.toLowerCase().equals(userRand.toLowerCase())) {
			printWriter.print("验证码错误!");
			return;
		} 
		String loginName = request.getParameter("username");
		String password = request.getParameter("password");
		
		MessageDigestPasswordEncoder mdpeSha = new MessageDigestPasswordEncoder("SHA-256"); 
		mdpeSha.setEncodeHashAsBase64(false);
		String shaPassword = mdpeSha.encodePassword(password, null);
		
		UsernamePasswordToken token = new UsernamePasswordToken(loginName, shaPassword);
		Subject currentUser = SecurityUtils.getSubject();
		org.apache.shiro.session.Session session1 = currentUser.getSession();
		log.info(session1.getTimeout());
		try {
			currentUser.login(token);
			if(currentUser.isAuthenticated()){
				Emp emp=empService.queryEmpByLoginName(loginName);
				session.setAttribute("currentUser", emp);
				log.info("登录成功:"+emp.getEname()+",sessionId:"+ session.getId());
				printWriter.print("true");
				return;
			}
		} catch (UnknownAccountException ex) {
				//用户名没有找到。
//				ex.printStackTrace();
				log.error("用户名没有找到:"+ex.getMessage(), ex);
				printWriter.print("用户名没有找到，请重新输入");
				return;

		} catch (IncorrectCredentialsException ex) {
				//用户名密码不匹配。
//				ex.printStackTrace();
				log.error("用户名密码不匹配:"+ex.getMessage(), ex);
				printWriter.print("用户名密码不匹配，请重新输入");
				return;
		}catch (AuthenticationException e) {
				//其他的登录错误
//				e.printStackTrace();
				log.error("认证异常:"+e.getMessage(), e);
				printWriter.print("认证异常，请重新输入");
				return;
		}
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(HttpServletRequest request,HttpServletResponse response){
		return "market/index";
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping(value = "/logOut")
	public String logOut(HttpServletRequest request,HttpServletResponse response) throws IOException{
		request.getSession().removeAttribute("currentUser");
        Subject currentUser = SecurityUtils.getSubject();  
        currentUser.logout();  
        String contextPath= request.getContextPath();
        System.out.println("contextPath: "+contextPath);
        //response.sendRedirect("market/login");
        //PrintWriter printWriter = response.getWriter();
       // printWriter.write("<script type='text/javascript'>window.parent.location='market/login'</script>");
        return "redirect:/login/loginPage";
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping(value = "/error", method = RequestMethod.GET)
	public String error(HttpServletRequest request,HttpServletResponse response){
        return "errors/error";
	}

}
